<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class CateController extends Controller
{
     /**
     * 显示无限极分类
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $cates = DB::table('cates')->get();

        $cates = $this->findSubTree($cates,0,0); 

        return view('wuxian.cate_list',['cates'=>$cates]);
    }

    /**
     * 创建添加框
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $cates = DB::table('cates')->get();
        // dd($cates);
        $cates = $this->findSubTree($cates,0,0); 

       return view('wuxian.cate',[
        'cates'=>$cates
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = ['pid'=>$request->pid,'name'=>$request->name];
        $res = DB::table('cates')->insert($data);
        return redirect()->back();
    }

    /**
     * 地址获取子栏目
     */
    protected function findSubTree($cates,$id=0,$lev=1)
    {
        $subtree = [];//子孙组
        foreach($cates as $v){
            if($v->pid == $id){
                $v->lev = $lev;
                $subtree[] = $v;
                $subtree = array_merge($subtree,$this->findSubTree($cates,$v->id,$lev+1));
                // dd($subtree);
            }
        }
        return $subtree;
    }
    /**
    *
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
